package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.entity.SysStoreEntity;
import com.example.model.page.PageData;
import com.example.mybatis.service.impl.CrudServiceImpl;
import com.example.dao.ZyCategoriesDao;
import com.example.dto.ZyCategoriesDTO;
import com.example.entity.CategoriesEntity;
import com.example.service.SysStoreService;
import com.example.service.CategoriesService;
import com.example.utils.ConvertUtils;
import com.example.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 分类表
 *
 * @author yyyyjinying 1020066395@qq.com
 * @since 1.0-SNAPSHOT 2025-04-27
 */
@Service
public class CategoriesServiceImpl extends CrudServiceImpl<ZyCategoriesDao, CategoriesEntity, ZyCategoriesDTO> implements CategoriesService {

    @Autowired
    private SysStoreService sysStoreService;

    @Override
    public QueryWrapper<CategoriesEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<CategoriesEntity> wrapper = new QueryWrapper<>();

        String storeId = (String)params.get("storeId");
        wrapper.eq(StringUtils.isNotBlank(storeId), "store_id", storeId);

        return wrapper;
    }

    @Override
    public void save(ZyCategoriesDTO dto) {
        CategoriesEntity entity = ConvertUtils.sourceToTarget(dto, CategoriesEntity.class);
        entity.setId(snowflake.nextId()); // 主键id可能有错误
        SysStoreEntity sysStoreEntity = sysStoreService.selectById(entity.getStoreId());
        Long tenantId = sysStoreEntity.getTenantId();
        entity.setTenantId(tenantId);
        baseDao.insert(entity);
    }
    @Override
    public PageData<ZyCategoriesDTO> page(Map<String, Object> params) {
        IPage<CategoriesEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        List<CategoriesEntity> records = page.getRecords();
        List<ZyCategoriesDTO> zyCategoriesDTOS = ConvertUtils.sourceToTarget(records, ZyCategoriesDTO.class);
        List<ZyCategoriesDTO> build = TreeUtils.build(zyCategoriesDTOS);
        return getPageData(build, page.getTotal(), currentDtoClass());
    }



}